import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:common_utils/common_utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/entity/banner_for_home_entity.dart';
import 'package:taonile/routers/routers.dart';

import '../entity/goods_area_category_entity.dart';
import '../entity/jingang_for_home_entity.dart';
import '../entity/product_entity.dart';
import '../http/api.dart';
import '../utils/string_utils.dart';
import '../views/store_home_module.dart';

class StoreIndex extends StatefulWidget {
  const StoreIndex({Key? key}) : super(key: key);

  @override
  State<StoreIndex> createState() => _StoreIndexState();
}

class _StoreIndexState extends State<StoreIndex> {
  //推荐商品
  List<ProductData> datas = [];
  var page = 1;

  //报单专区的配置
  List<GoodsAreaCategoryData> goodsAreaCates = [];

  //金刚区
  List<JingangForHomeData> jingangList = [];

  //轮播
  List<BannerForHomeData> banners = [];

  bool isLoopBanner = false;

  List<HotCity> hotCity = [
    HotCity(name: '深圳市', id: '440300'),
    HotCity(name: '北京市', id: '110100'),
    HotCity(name: '上海市', id: '310100'),
    HotCity(name: '广州市', id: '440100')
  ];

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  getData() async {
    await getBannerList();
    await getJingangList();
    await getAreaCategoryList();
    await getProducts();
    await getLocal();
  }

  getBannerList() async {
    dynamic result = await Api.bannerForHome({});
    BannerForHomeEntity entity = BannerForHomeEntity.fromJson(result);
    setState(() {
      banners.clear();
      banners.addAll(entity.data);
      Future.delayed(const Duration(milliseconds: 1500), () {
        setState(() {
          isLoopBanner = true;
        });
      });
    });
  }

  getJingangList() async {
    dynamic result = await Api.jingangForHome();
    JingangForHomeEntity entity = JingangForHomeEntity.fromJson(result);
    setState(() {
      jingangList.clear();
      jingangList.addAll(entity.data);
    });
  }

  getAreaCategoryList() async {
    dynamic result = await Api.goodsAreaCategoryList();
    GoodsAreaCategoryEntity entity = GoodsAreaCategoryEntity.fromJson(result);
    setState(() {
      goodsAreaCates.clear();
      goodsAreaCates.addAll(entity.data);
    });
  }

  getProducts() async {
    dynamic result = await Api.goodsList({'page': page.toString(), 'size': '20'});
    ProductEntity entity = ProductEntity.fromJson(result);
    setState(() {
      if (page == 1) {
        datas.clear();
      }
      if (entity.data.isNotEmpty) {
        page++;
        datas.addAll(entity.data);
      }
    });
  }

  getLocal() async {
    if (await Permission.location.request().isGranted) {
      // Either the permission was already granted before or the user just granted it.
      LogUtil.v('获得了定位权限');

    }
  }

  var tags = ['休闲、足浴', '2000人关注'];

  getSearchGuess(int index) {
    return InkWell(
      onTap: () {},
      child: Container(
        width: StringUtils.getStringWidth(tags[index], 19.sp) + 15,
        height: 30.w,
        decoration: BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(20.w),
          border: Border.all(color: Config.colorMain, width: 1.w),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              tags[index],
              style: TextStyle(color: Config.colorMain, fontSize: 18.sp),
            ),
          ],
        ),
      ),
    );
  }

  //返回商品列表item
  getListItem(int index) {
    return InkWell(
      onTap: () {
        Routes.navigateTo(context, Routes.storeDetail, params: {'storeId': datas[index].id});
      },
      child: Container(
        width: double.infinity,
        height: 175.w,
        decoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.circular(10.w),
        ),
        padding: EdgeInsets.all(15.w),
        margin: EdgeInsets.only(bottom: 20.w),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.all(
                Radius.circular(12.w),
              ),
              child: CachedNetworkImage(
                imageUrl: datas[index].mainImg,
                fit: BoxFit.fill,
                width: 120.w,
                height: 120.w,
                errorWidget: (context, url, error) {
                  return Image.asset(
                    'assets/images/bg_default_400.png',
                    width: 120.w,
                    height: 120.w,
                    fit: BoxFit.fill,
                  );
                },
              ),
            ),
            Container(
              padding: EdgeInsets.only(left: 15.w),
              // decoration: const BoxDecoration(color: Config.),
              width: 560.w,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '雅诗兰黛官方旗舰店',
                        softWrap: false,
                        style: TextStyle(color: Config.colorText1, fontSize: 26.sp),
                      ),
                      Text(
                        '09:00-22:00',
                        softWrap: false,
                        style: TextStyle(color: Config.colorText3, fontSize: 23.sp),
                      ),
                    ],
                  ),
                  Padding(padding: EdgeInsets.only(top: 16.w)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Wrap(
                        spacing: 15.w,
                        runSpacing: 15.w,
                        children: List.generate(tags.length, (index) => getSearchGuess(index)),
                      ),
                      Row(
                        children: [
                          Icon(
                            Icons.location_on_outlined,
                            size: 25.w,
                            color: Config.colorText1,
                          ),
                          Text(
                            '500m',
                            softWrap: false,
                            style: TextStyle(color: Config.colorText1, fontSize: 23.sp),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Padding(padding: EdgeInsets.only(top: 16.w)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '周一至周五可消费',
                        softWrap: false,
                        style: TextStyle(color: Config.colorText3, fontSize: 23.sp),
                      ),
                      Text(
                        '999人已消费',
                        softWrap: false,
                        style: TextStyle(color: Config.colorText3, fontSize: 23.sp),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget getJingangItem(int index, Function() onTap) {
    return InkWell(
      onTap: onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CachedNetworkImage(
            imageUrl: jingangList[index].imgPath,
            fit: BoxFit.fill,
            width: 75.w,
            height: 75.w,
            errorWidget: (context, url, error) {
              return Image.asset(
                'assets/images/bg_default_400.png',
                width: 75.w,
                height: 75.w,
                fit: BoxFit.fill,
              );
            },
          ),
          Padding(
            padding: EdgeInsets.only(top: 8.w),
          ),
          Text(jingangList[index].name,
              style: TextStyle(fontSize: 21.sp, color: Config.colorText1)),
        ],
      ),
    );
  }

  ///
  /// 切换城市
  getCityResult() async {
    Result? result = await CityPickers.showCitiesSelector(
      context: context,
      theme: Theme.of(context).copyWith(),
      title: '定位：深圳市',
      // useSearchAppBar: true,
      hotCities: hotCity,
      locationCode: '440300',
      sideBarStyle: BaseStyle(
        color: Config.colorText1,
        fontSize: 26.w,
        backgroundColor: Colors.transparent,
        backgroundActiveColor: Colors.transparent,
        activeColor: Config.colorMain,
      ),
    );
    if (result != null) {
      print(result);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: const EdgeInsets.all(0),
        width: double.infinity,
        decoration: const BoxDecoration(color: Config.colorBg2),
        height: double.infinity,
        child: Stack(
          children: [
            Container(
              padding: EdgeInsets.only(top: 105.w),
              child: EasyRefresh.builder(
                header: const MaterialHeader(),
                footer: const MaterialFooter(),
                onRefresh: () async {
                  await getBannerList();
                  await getJingangList();
                  await getAreaCategoryList();
                  page = 1;
                  await getProducts();
                },
                onLoad: () async {
                  await getProducts();
                },
                childBuilder: (context, physics) {
                  return ListView(
                    scrollDirection: Axis.vertical,
                    // controller: controller,
                    physics: physics,
                    children: [
                      Container(
                        //轮播
                        margin: EdgeInsets.only(left: 25.w, right: 25.w),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10.w),
                        ),
                        height: 306.w,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(10.w),
                          child: Swiper(
                            itemBuilder: (BuildContext context, int index) {
                              return CachedNetworkImage(
                                imageUrl: banners[index].imgPath,
                                fit: BoxFit.fill,
                                errorWidget: (context, url, error) {
                                  return Image.asset(
                                    'assets/images/bg_default_400.png',
                                    width: 700.w,
                                    height: 306.w,
                                    fit: BoxFit.fill,
                                  );
                                },
                              );
                            },
                            onTap: (index) {
                              // Routes.navigateTo(context, Routes.webView, params: {
                              //   'pageTitle': banners[index].id,
                              //   'webUrl': banners[index].link
                              // });
                            },
                            autoplayDelay: 4000,
                            autoplay: isLoopBanner,
                            loop: isLoopBanner,
                            layout: SwiperLayout.DEFAULT,
                            itemCount: banners.length,

                            // viewportFraction: 0.7,
                            // scale: 0.8,
                            pagination: SwiperPagination(
                              builder: DotSwiperPaginationBuilder(
                                  // size: Size(20.w, 4.w),
                                  // activeSize: Size(20.w, 4.w),
                                  size: 15.w,
                                  activeSize: 15.w,
                                  activeColor: Config.colorMain,
                                  color: Config.colorWhite),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        //金刚区
                        width: double.infinity,
                        margin: EdgeInsets.only(top: 30.w),
                        child: SizedBox(
                          height: jingangList.length > 5 ? 280.w : 130.w,
                          child: GridView.builder(
                            padding: EdgeInsets.symmetric(vertical: 0.w, horizontal: 0.w),
                            physics: const NeverScrollableScrollPhysics(),
                            scrollDirection: Axis.vertical,
                            itemCount: jingangList.length,
                            itemBuilder: (context, index) {
                              return getJingangItem(index, () async {
                                Routes.navigateTo(context, Routes.storeList);
                              });
                            },
                            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                              mainAxisSpacing: 0.w,
                              childAspectRatio: 1,
                              crossAxisSpacing: 0,
                              crossAxisCount: 5,
                            ),
                          ),
                        ),
                      ),
                      getMallStoreModule2(context, goodsAreaCates),
                      Container(
                        margin: EdgeInsets.only(top: 40.w, left: 25.w, right: 25.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 140.w,
                              height: 60.w,
                              margin: EdgeInsets.only(right: 20.w),
                              child: Divider(
                                color: Config.colorText3,
                                height: 50.w,
                                thickness: 2.w,
                              ),
                            ),
                            Text(
                              '附近商家',
                              style: TextStyle(color: Config.colorText1, fontSize: 28.sp),
                            ),
                            Container(
                              width: 140.w,
                              height: 60.w,
                              margin: EdgeInsets.only(left: 20.w),
                              child: Divider(
                                color: Config.colorText3,
                                height: 50.w,
                                thickness: 2.w,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.fromLTRB(20.w, 30.w, 20.w, 20.w),
                        width: double.infinity,
                        decoration: const BoxDecoration(color: Colors.transparent),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(
                              width: double.infinity,
                              child: ListView.builder(
                                padding: EdgeInsets.symmetric(horizontal: 0.w),
                                itemCount: datas.length,
                                shrinkWrap: true,
                                scrollDirection: Axis.vertical,
                                physics: const NeverScrollableScrollPhysics(),
                                itemBuilder: (BuildContext context, int index) {
                                  return getListItem(index);
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
            Container(
              height: 140.w,
              padding: EdgeInsets.only(top: 60.w, left: 25.w, right: 25.w),
              decoration: const BoxDecoration(color: Config.colorBg2),
              child: Row(
                children: [
                  InkWell(
                    child: Text(
                      '深圳市',
                      style: TextStyle(color: Config.colorText1, fontSize: 26.w),
                    ),
                    onTap: () async {
                      getCityResult();
                    },
                  ),
                  Icon(
                    Icons.arrow_forward_ios,
                    color: Config.colorText2,
                    size: 22.w,
                  ),
                  Container(
                    height: 46.w,
                    width: 560.w,
                    decoration: BoxDecoration(
                        color: Config.colorWhite, borderRadius: BorderRadius.circular(24.w)),
                    padding: EdgeInsets.symmetric(horizontal: 20.w),
                    margin: EdgeInsets.only(left: 15.w, right: 15.w),
                    child: InkWell(
                      onTap: () {
                        Routes.navigateTo(context, Routes.searchIndex, params: {'source': '0'});
                      },
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Icon(
                            Icons.search,
                            size: 28.w,
                            color: Config.colorText3,
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 10.w),
                          ),
                          Text(
                            "请输入商店名称",
                            style:
                                TextStyle(fontSize: 22.sp, height: 1.3, color: Config.colorText3),
                          )
                        ],
                      ),
                    ),
                  ),
                  // InkWell(
                  //   child: Text(
                  //     '消费记录',
                  //     style: TextStyle(color: Config.colorText1, fontSize: 22.w),
                  //   ),
                  //   onTap: () {
                  //     Routes.navigateTo(context, Routes.productClassify);
                  //   },
                  // ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
